import 'dart:convert';

import 'package:leader_help/utils/img_util.dart';
import 'package:leader_help/utils/storage.dart';
import 'package:get/get.dart';
import '../keys.dart';
import '../global.dart';
import 'state.dart';
import 'user.dart';

class UserController extends GetxController {
  final state = UserState();
  @override
  void onInit() {
    super.onInit();
    var _token = GlobalState().token;
    if (_token != null) {
      var _userStr = SpUtil().getStr(key_store_user);
      if (_userStr.isNotEmpty) {
        var _userJson = jsonDecode(_userStr);
        state.user = User.fromJson(_userJson);
        state.userObs.value = state.user!;
        state.userObs.refresh();
      }
    }
    fakeInfo();
  }

  void configUser(Map<String, dynamic> userJson) {
    state.user = User.fromJson(userJson);
    state.userObs.value = state.user!;
    state.userObs.refresh();
    save();
  }

  void fakeInfo() {
    isLogin = true;
    state.user =
        User(name: '楼阳生', avater: '楼阳生.png'.imgPathHome, post: '省委书记、省人大常委会主任');
    state.userObs.value = state.user!;
  }

  final isLoginObs = false.obs;
  set isLogin(bool value) => isLoginObs.value = value;
  bool get isLogin => isLoginObs.value;

  final isAtLoginObs = true.obs;
  set isAtLogin(bool value) => isAtLoginObs.value = value;
  bool get isAtLogin => isAtLoginObs.value;

  void save() {
    if (state.user != null) {
      var _json = state.user!.toJson();
      SpUtil().setJSON(key_store_user, jsonEncode(_json));
    }
  }
}
